let autologin = function(resolve, reject) { // 从后台获取sessionID
  let roleType = uni.getStorageSync('roleType')
	let userId = uni.getStorageSync('userId')
	let departId = uni.getStorageSync('departId')
	if( roleType === '' || userId === '' || departId === '') { // 用户还没登录成功过
		reject({state: 0});
		return
	}
	this.http.POST({
  	name: 'autologin',
  	params: {
			roleType, userId, departId
		}
  }).then(res => {
  	if (res.result == 'success') {
			uni.setStorageSync('sessionId', res.data.sessionId)
  		resolve(res)
  	} else {
      reject({state: 1});
    }
  })
  .catch(() => {
    this.catchError('autologin');
  })
};
let catchError = function() {
  let args = Array.prototype.slice.call(arguments);
  let [funcName, ...rest] = args;
  uni.getNetworkType({
    success: (res) => {
      const networkType = res.networkType
      if (networkType === 'none') { // 客户端网络异常
        uni.showModal({
          title: '温馨提示',
          showCancel: false,
          content: '网络连接超时，请检查后重试！',
          confirmText: '重试',
          success: (res) => {
            if (res.confirm) {
              this[funcName](...rest);
            }
          }
        });
      } else {
        uni.showModal({
          title: '温馨提示',
          showCancel: false,
          content: '服务异常，请稍后重试！',
          confirmText: '重试',
          success: (res) => {
            if (res.confirm) {
              this[funcName](...rest);
            }
          }
        });
      }
    },
    fail: () => {
      uni.showModal({
        content: '微信接口调用失败',
        showCancel: false,
        confirmText: '重试',
        success (res) {
          if (res.confirm) {
            this[funcName](...rest);
          }
        }
      })
    }
  })
};

function login(option) {
  this.$store.state.loggedIn = new Promise((resolve, reject) => {
    // 绑定上下文环境
		this.catchError = catchError.bind(this)
    this.autologin = autologin.bind(this);
    // 开始执行
    this.autologin(resolve, reject);
  })
}
export default login